package com.cloud.zuul.controller;

import com.cloud.zuul.entity.RestEntity;
import com.cloud.zuul.utils.OauthUtils;
import com.lwj.framework.constant.Constant;
import com.lwj.framework.entity.AuthEntity;
import com.lwj.framework.entity.AuthProperties;
import com.lwj.framework.rest.RestClient;
import com.lwj.framework.security.AuthUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2RefreshToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.ConsumerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

@Api("用户接口")
@RestController
@RequestMapping(value = "/user")
public class UserController {
	final static Logger logger = LoggerFactory.getLogger(UserController.class);
	@Value("${spring.application.name}")
	protected String securityServerId;

	@Autowired
	protected AuthProperties authProperties;

	@Autowired
	protected RestTemplate restTemplate;

	@Autowired
	protected TokenStore tokenStore;

	@Autowired
	protected ConsumerTokenServices consumerTokenServices;

	@PermitAll
	@ApiOperation(value = "获取token")
	@RequestMapping(value = "/accessToken", method = { RequestMethod.POST, RequestMethod.GET })
	public RestEntity accessToken(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("clientname") String clientName, @RequestParam("username") String username,
			@RequestParam("password") String password) {
		OAuth2AccessToken token = null;
		try {
			AuthEntity authEntity = authProperties.getAuthByName(clientName);
			MultiValueMap<String, String> head = OauthUtils.getHttpHeaders(authEntity);
			MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
			param.add("grant_type", "password");
			param.add("username", username);
			param.add("password", password);
			token = RestClient.postForm(restTemplate, securityServerId + "/oauth/token", head, param,
					OAuth2AccessToken.class);
		} catch (Exception e) {
//			logger.error("accessToken error", e);
			return RestEntity.error("系统错误");
		}
		return RestEntity.success(token);
	}

	@PermitAll
	@ApiOperation(value = "刷新token")
	@RequestMapping(value = "/refreshToken", method = { RequestMethod.POST, RequestMethod.GET })
	public RestEntity refreshToken(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("refreshToken") String refreshToken) {
		OAuth2AccessToken token = null;
		try {
			OAuth2RefreshToken oauth2RefreshToken = tokenStore.readRefreshToken(refreshToken);
			OAuth2Authentication oauth2Authentication = tokenStore.readAuthenticationForRefreshToken(oauth2RefreshToken);
			String clientid = oauth2Authentication.getOAuth2Request().getClientId();
			AuthEntity authEntity = authProperties.getAuthById(clientid);
			MultiValueMap<String, String> head = OauthUtils.getHttpHeaders(authEntity);
			MultiValueMap<String, String> param = new LinkedMultiValueMap<String, String>();
			param.add("grant_type", "refresh_token");
			param.add("refresh_token", refreshToken);
			token = RestClient.postForm(restTemplate, securityServerId + "/oauth/token", head, param,
					OAuth2AccessToken.class);
		} catch (Exception e) {
			logger.error("refreshToken error", e);
			return RestEntity.error("用户不存在");
		}
		return RestEntity.success(token);
	}

	@PermitAll
	@ApiOperation(value = "注销token")
	@RequestMapping(value = "/revokeToken", method = { RequestMethod.POST, RequestMethod.GET })
	public boolean revokeToken(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("accessToken") String accessToken) {
		boolean resulte = false;
		try {
			OAuth2AccessToken oauth2AccessToken = tokenStore.readAccessToken(accessToken);
			consumerTokenServices.revokeToken(oauth2AccessToken.getValue());
			resulte = true;
		} catch (Exception e) {
			logger.error("revokeToken error", e);
		}
		return resulte;
	}
	@GetMapping("test")
    public String test(){
		return "test";
	}

	public static void main(String[] args) {

	}
}
